import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

import { Hero, HeroService } from './hero.service';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html',
  // styleUrls: ['./hero.component.css']
})
export class HeroListComponent implements OnInit {
  isAddHeroVisible = false;
  validateForm: FormGroup;

  heroes: Hero[] = [];
  options: any[] = []

  constructor(
    private fb: FormBuilder,
    private heroService: HeroService,
    private route: ActivatedRoute,
    private router: Router,
  ) { }

  ngOnInit() {
    this.validateForm = this.fb.group({
      name: [ null, [ Validators.required ] ],
      type: [ 1, [ Validators.required ] ],
    });

    this.getHeros();
    this.getOptions();

  }

  getOptions() {
    this.options = this.heroService.getOptions();
  }
  getHeros() {
    this.heroService.getHeroes().then(heros => this.heroes = heros);
  }

  // 添加英雄
  openAddHero(hero?: any) {
    if (hero) {
      this.validateForm.reset({
        name: hero.name,
        type: this.heroService.getOptionValue(hero.type)
      });
    } else {
      this.validateForm.reset({
        type: 1
      });
    }
    this.isAddHeroVisible = true;
  }
  addHeroCancel() {
    this.isAddHeroVisible = false;
  }
  addHeroConfirm() {
    // this.isAddHeroVisible = false;
    // console.log(this.validateForm);
    for (const field of Object.keys(this.validateForm.controls)) {
      this.validateForm.controls[field].markAsDirty();
    }

    if (this.validateForm.valid) {
      const hero = {
        id: Date.now(),
        name: this.validateForm.value.name,
        type: this.heroService.getOptionLabel(this.validateForm.value.type)
      };
      this.heroes.push(hero);
      this.addHeroCancel();
    } else {

    }
  }
  getFormControl(name) {
    return this.validateForm.get(name);
  }

  deleteHero(hero: any) {
    const i = this.heroes.indexOf(hero);
    this.heroes.splice(i, 1);
  }

  goToDetail(heroId) {
    this.router.navigate([heroId], { relativeTo: this.route });
  }

}
